import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yurun_smartmerchants/generated/json/base/json_convert_content.dart';
import 'package:yurun_smartmerchants/models/good_list_entity.dart';
import 'package:yurun_smartmerchants/models/inventory_detail_entity.dart';
import 'package:yurun_smartmerchants/net/ApiInterface.dart';
import 'package:yurun_smartmerchants/res/colours.dart';
import 'package:yurun_smartmerchants/utils/app_size.dart';
import 'package:yurun_smartmerchants/utils/loading_utils.dart';
import 'package:yurun_smartmerchants/view/EmptyView.dart';
import 'package:yurun_smartmerchants/view/custom_loadmore_footer.dart';
import 'package:yurun_smartmerchants/view/custom_refresh_header.dart';

class InventoryDetailsPage extends StatefulWidget{
  final GoodListContent goodContent;

  InventoryDetailsPage({this.goodContent});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _InventoryDetailsPageState();
  }

}

class _InventoryDetailsPageState extends State<InventoryDetailsPage>{
  List<InventoryDetailContent> detailList = List();
  int page = 0;
  final int size = 15;
  bool isRefreshOrLoad = false;
  bool empty = false;
  String operationType = '';

  EasyRefreshController _easyRefreshController = EasyRefreshController();

  VerticalDivider _verticalDivider = VerticalDivider(
    thickness: AppSize.width(2),
    width: AppSize.width(2),
    color: Colours.color_dcdcdc,
    indent: AppSize.height(20),
    endIndent: AppSize.height(20),
  );

  void statusRefreshLoad(load,last){
    if(page == 0){
      _easyRefreshController.finishRefresh(success: load);
    }
    _easyRefreshController.finishLoad(success: load,noMore: last);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _getInventoryDetails();
    });
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Container(
        color: Colours.app_background,
        child: Column(
          children: <Widget>[
            Container(
              color: Color(0xfffcf7e9),
              margin: EdgeInsets.only(top: AppSize.height(20)),
              height: AppSize.height(66),
              child: Row(
                children: <Widget>[
                  Expanded(
                      flex:1,
                      child: Container(
                        alignment: Alignment.center,
                        child: Text('批次号',style: TextStyle(fontSize: AppSize.sp(22),color: Colours.color_434343),),
                      )),
                  _verticalDivider,
                  Expanded(
                      flex:1,
                      child: Container(
                        alignment: Alignment.center,
                        child: Text('时间',style: TextStyle(fontSize: AppSize.sp(22),color: Colours.color_434343),),
                      )),
                  _verticalDivider,
                  Expanded(
                      flex:1,
                      child: Container(
                        alignment: Alignment.center,
                        child: Text('事由',style: TextStyle(fontSize: AppSize.sp(22),color: Colours.color_434343),),
                      )),
                  _verticalDivider,
                  Expanded(
                      flex:1,
                      child: Container(
                        alignment: Alignment.center,
                        child: Text('数量',style: TextStyle(fontSize: AppSize.sp(22),color: Colours.color_434343),),
                      )),
                  _verticalDivider,
                  Expanded(
                      flex:1,
                      child: Container(
                        alignment: Alignment.center,
                        child: Text('剩余库存',style: TextStyle(fontSize: AppSize.sp(22),color: Colours.color_434343),),
                      ))
                ],
              ),
            ),
            Expanded(
                child: CupertinoScrollbar(
                    child: EasyRefresh(
                        controller: _easyRefreshController,
                        header: CustomRefreshHeader(),
                        footer: CustomLoadFooter(),
                        emptyWidget: empty ? EmptyView(content: '暂无数据',) : null,
                        onRefresh: () async {
                          isRefreshOrLoad = true;
                          page = 0;
                          _getInventoryDetails();
                        },
                        onLoad: () async {
                          isRefreshOrLoad = true;
                          page ++;
                          _getInventoryDetails();
                        },
                        child: ListView.builder(
                          physics: BouncingScrollPhysics(),
                          itemBuilder: (BuildContext context, int index){
                            return listItemView(index);
                          },
                          itemCount: detailList.length,
                        )
                    )
                )
            )
          ],
        ),
      ),
    );
  }

  Widget listItemView(index){
    int type = detailList[index].operation;
    if(type == 0){
      operationType = '入库';
    }else if(type == 1){
      operationType = '出库';
    }else if(type == 2){
      operationType = '损耗';
    }
    return Container(
      color: index % 2 == 0 ? Colors.white : Color(0xfff9f9f9),
      height: AppSize.height(66),
      child: Row(
        children: <Widget>[
          Expanded(
              flex:1,
              child: Container(
                alignment: Alignment.center,
                child: Text(detailList[index].batchNo,style: TextStyle(fontSize: AppSize.sp(24),color: Colours.color_434343),overflow: TextOverflow.ellipsis,maxLines: 1,),
              )),
          Expanded(
              flex:1,
              child: Container(
                alignment: Alignment.center,
                child: Text(detailList[index].modifiedTime,style: TextStyle(fontSize: AppSize.sp(24),color: Colours.color_434343),overflow: TextOverflow.ellipsis,maxLines: 1,),
              )),
          Expanded(
              flex:1,
              child: Container(
                alignment: Alignment.center,
                child: Text(operationType,style: TextStyle(fontSize: AppSize.sp(24),color: Colours.color_434343),),
              )),
          Expanded(
              flex:1,
              child: Container(
                alignment: Alignment.center,
                child: Text(
                  detailList[index].quantity >= 0 ? '+' + detailList[index].quantity.toString() + detailList[index].packageContainer : '-' + detailList[index].quantity.toString() + detailList[index].packageContainer,
                  style: TextStyle(fontSize: AppSize.sp(24),color: Colours.color_434343),),
              )),
          Expanded(
              flex:1,
              child: Container(
                alignment: Alignment.center,
                child: Text(detailList[index].surplus.toString() + detailList[index].packageContainer,style: TextStyle(fontSize: AppSize.sp(24),color: Colours.color_434343),),
              )),
        ],
      ),
    );
  }

  void _getInventoryDetails(){
    int id = widget.goodContent.id;
    if(!isRefreshOrLoad){
      LoadingUtil.showLoading(context,tip: '加载中...');
    }
    ApiInterface.getInventoryDetail(id,page,size).then((value) {
      InventoryDetailEntity inventoryDetailEntity = JsonConvert.fromJsonAsT<InventoryDetailEntity>(value);
      setState(() {
        if(page == 0){
          detailList.clear();
        }
        if(inventoryDetailEntity.content != null && inventoryDetailEntity.content.length > 0){
          detailList.addAll(inventoryDetailEntity.content);
        }
        if(detailList.length == 0){
          empty = true;
        }else{
          empty = false;
        }
      });
      statusRefreshLoad(true, inventoryDetailEntity.last);
      if (detailList.length > 0) {
        if (isRefreshOrLoad && page == 0) {
          showToast("刷新成功");
        } else if (inventoryDetailEntity.last && page > 0) {
          showToast("暂无更多数据");
        }
      }
    }).catchError((error){
      statusRefreshLoad(false, true);
    }).whenComplete(() => LoadingUtil.hideLoading(context));
  }
}